package com.fingard.dsp.bank.directbank.czb01;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;
import com.fingard.util.PdfGenerateUtil;
import com.fingard.util.SmbFileUtil;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class CZB01Receipt extends CZB01Base implements IReceipt {
    // 交易传入的数据
    private String receiptSaveToMainDir = "";

    public RetAtsReceipt qryReceipt(final ReqQryReceipt p_reqReceipt) throws Exception {
        // 回单查询返回ATS的对象
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
        if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
            if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                    downReceipt(p_reqReceipt);
                    retAts.respInfo = "后台处理中";
                    retAts.respCode = "0";
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "DSPSystem未配置回单文件推送地址";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "DSPSystem未配置回单文件共享目录";
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "DSPSystem未配置回单文件下载保存主目录";
        }
        retAts.writeRetToATS();
        return retAts;
    }

    /**
     * 下载回单
     */
    public void downReceipt(ReqQryReceipt p_reqReceipt) throws Exception {
        Calendar tmpCalendarFrom = Calendar.getInstance();
        tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());

        Calendar tmpCalendarTo = Calendar.getInstance();
        tmpCalendarTo.setTime(p_reqReceipt.getDateTo());

        int tmpIntDateFrom = 0;
        int tmpIntDateTo = 0;

        //按自然日循环查询
        while (tmpIntDateFrom <= tmpIntDateTo) {

            CZB01Header bankHeader = new CZB01Header();

            bankHeader.transCode = "200119";


            bankHeader.reqSeqNo = getQryTransID();

            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, bankHeader);

            xmlWriter.writeStartElement("body");
            xmlWriter.writeElementString("accno", p_reqReceipt.actNum);
            xmlWriter.writeElementString("date", Format.Date8Format.format(tmpCalendarFrom.getTime()));
            xmlWriter.writeEndDocument();
            WriteBankLogLn("查询日期：" + Format.Date8Format.format(tmpCalendarFrom.getTime()));
            //返回到ATS的请求String
            StringBuilder json = new StringBuilder();
            if(getBankConfig().getValueAsBool("receiptPushHasTenantId")){
                json.append("tenantId="+FGBiz.dspCenter.dspSet.tenant+"&transType=downloadreceipt&data={\"rows\":[");
            }else{
                json.append("transType=downloadreceipt&data={\"rows\":[");
            }
            int tmpFileCount = 0;//记录上传成功的回单数
            StringBuilder sb = new StringBuilder();
            // 测试用
            //saveToMainDir("D:\\getToWork\\14-filesForDevelop\\FnGrd01\\回单下载2.zip",tmpCalendarFrom.getTime(),
            //p_reqReceipt.actNum, bankHeader.CorpBankCode);
            // 测试用

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                    if (tmpRetCode.equals("0000")) {
                        String total_num = tmpBkReader.getFirstText("/ap/body/total_num");
                        if (!total_num.equals("0")) {
                            //未知返回file_name类型
                            String fileName = tmpBkReader.getFirstText("/ap/body/file_name");
                            String download = StringHelper.trimEnd(bankFront.bkTransFolder, "/") + File.separator;
                            String destPath = download + Format.Date6YearMonth.format(new Date()) + File.separator + Format.Date8Format.format(new Date()).substring(6,8) + File.separator +
                                    "CZB01" +File.separator + p_reqReceipt.actNum + File.separator;
                            FileHelper.copyFile(download + fileName,destPath + fileName);
                            WriteBankLogLn("开始解析PDF文件");
                            String[] params = {"打印申请人:", "业务流水号", "交易时间", "主机流水号", "备注", "全国统一服务电话", "交易金额：", "客户电子回单（", "） 防伪码", "摘要：", "回单编号", "户名：", "本凭证作为", " 账号:", "开户银行:", "业务种类", "业务渠道", "防伪码：", "业务类型","账号:"};
                            @SuppressWarnings("unchecked")
                            List<String> fileNames = PdfGenerateUtil.splitPDF(destPath + fileName, params);
                            String actCur = getBankConfig().getMapValueByKey("elereceiptAccountInfo", p_reqReceipt.actNum);
                            if (StringHelper.isNullOrEmpty(actCur)) {
                                actCur = "1";
                            }
                            for (String pfile : fileNames) {
                                File receiptDir = new File(destPath + fileName.substring(0, fileName.lastIndexOf(".pdf")) + File.separator + pfile);
                                if (receiptDir.isDirectory()) {
                                    String[] nextDir = FileHelper.listFiles(receiptDir.getPath());
                                    for (String sfile : nextDir) {
                                        File receiptDir_s = new File(receiptDir.getPath() + File.separator + sfile);
                                        int result = -1;
                                        String ftpFilePath="";
                                        String AtsFilePath = "";
                                        String newFilePath = Format.Date8Format.format(new Date()) + "/";
                                        if(!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)){
                                            if ("localhost".equals(SmbFileUtil.getUploadType())) {//上传到本地目录
                                                String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                                WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                                result = FileHelper.copyFile(receiptDir_s.getPath(), shareDir + newFilePath + receiptDir_s.getName());
                                                AtsFilePath = newFilePath + receiptDir_s.getName();//回单文件仓库存储路径
                                            } else {//上传到共享文件夹
                                                WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                result = SmbFileUtil.smbUploading(receiptDir_s.getPath(), newFilePath,
                                                        FGBiz.dspCenter.dspSet.receiptShareDir);
                                                AtsFilePath = newFilePath + receiptDir_s.getName();//回单文件仓库存储路径
                                            }
                                        }else {
                                            //ftp服务器
                                            FtpSet ftpSet3 = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                            WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet3.upDir);
                                            AtsFilePath = newFilePath + receiptDir_s.getName();//回单文件仓库存储路径
                                            //上传ftp服务器的地址
                                            ftpFilePath = StringHelper.trimEndFileSp(ftpSet3.upDir) + "/" +AtsFilePath;
                                            WriteBankLogLn("开始将回单"+receiptDir_s.getPath()+"上传至"+ftpFilePath);
                                            //上传至ftp
                                            result = FtpUtil.ftpUploading(ftpSet3, receiptDir_s.getPath(), ftpFilePath);
                                        }

                                        if (result == 0 || result == 1) {
                                            tmpFileCount++;
                                            if (result == 0) {
                                                WriteBankLogLn("文件上传成功");
                                            } else {
                                                WriteBankLogLn("文件已存在共享目录无需重复上传");
                                            }
                                            String[] receiptFileName_no = sfile.split("_");
                                            // 推送数据给ATS处理
                                            String wayFlag = receiptFileName_no[1].equals("借") ? "1" : "2";
                                            json.append("{");
                                            json.append("\"actNum\":\"" + p_reqReceipt.actNum + "\",");
                                            json.append("\"actCur\":\"" + actCur + "\",");
                                            json.append("\"receiptCode\":\"" + receiptFileName_no[0] + "\",");// 回单编号
                                            json.append("\"receiptType\":\"" + "" + "\",");// 回单类型 1：存款回单；2：取款回单；3：转账回单；4：缴税回单；5：收费回单；6定期回单；7：活期回单
                                            json.append("\"receiptState\":\"" + "" + "\",");// 回单状态 1：正常；2：冲正；3：被冲正；4：当日冲正
                                            json.append("\"oppActName\":\"" + receiptFileName_no[4] + "\",");
                                            json.append("\"oppActNum\":\"" + receiptFileName_no[5].replace(".pdf", "") + "\",");
                                            json.append("\"amount\":\"" + receiptFileName_no[1] + "\",");
                                            json.append("\"moneyway\":\"" + wayFlag + "\",");
                                            json.append("\"tranSeqNo\":\"" + "" + "\",");
                                            json.append("\"tranCode\":\"" + "" + "\",");// 交易码?
                                            json.append("\"tranDate\":\"" + receiptFileName_no[3] + "\",");
                                            json.append("\"filePath\":\"" + AtsFilePath + "\",");// 回单文件仓库存储路径
                                            json.append("\"fileType\":\"1\"");
                                            json.append("},");
                                            sb.append(pfile + ",");
                                        } else {
                                            WriteBankLogLn("上传文件至共享目录失败，请检查共享目录配置是否正确");
                                        }
                                    }
                                } else {
                                    int result = -1;
                                    String ftpFilePath="";
                                    String AtsFilePath = "";
                                    String newFilePath = Format.Date6YearMonth.format(new Date()) +"/" + Format.Date8Format.format(new Date()).substring(6,8) + "/" +
                                            "CZB01" +"/" + p_reqReceipt.actNum + "/";
                                    if(!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)){
                                        if ("localhost".equals(SmbFileUtil.getUploadType())) {//上传到本地目录
                                            String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                            WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                            result = FileHelper.copyFile(receiptDir.getPath(), shareDir + newFilePath + receiptDir.getName());
                                            AtsFilePath = newFilePath + receiptDir.getName();//回单文件仓库存储路径
                                        } else {// 上送到共享文件夹
                                            WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                            String shareDir = FGBiz.dspCenter.dspSet.receiptShareDir;
                                            result = SmbFileUtil.smbUploading(receiptDir.getPath(), newFilePath, shareDir);
                                            AtsFilePath = newFilePath + receiptDir.getName();//回单文件仓库存储路径
                                        }
                                    }else {
                                        //ftp服务器
                                        FtpSet ftpSet3 = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                        WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet3.upDir);
                                        AtsFilePath = newFilePath + receiptDir.getName();//回单文件仓库存储路径
                                        //上传ftp服务器的地址
                                        ftpFilePath = StringHelper.trimEndFileSp(ftpSet3.upDir) + "/" +AtsFilePath;
                                        WriteBankLogLn("开始将回单"+receiptDir.getPath()+"上传至"+ftpFilePath);
                                        //上传至ftp
                                        result = FtpUtil.ftpUploading(ftpSet3, receiptDir.getPath(), ftpFilePath);
                                    }

                                    if (result == 0 || result == 1) {
                                        if (result == 0) {
                                            WriteBankLogLn("文件上传成功");
                                        } else {
                                            WriteBankLogLn("文件已存在，不需要重复上传");
                                        }
                                        //143534053453_3202.25_借_2019-05-29_上海开元企业经营管理有限公司_03801390040000333.pdf
                                        String[] receiptFileName_no = pfile.split("_");
                                        if (result == 0 || result == 1) {
                                            tmpFileCount++;
                                            if (result == 0) {
                                                WriteBankLogLn("文件上传成功");
                                            } else {
                                                WriteBankLogLn("文件已存在共享目录无需重复上传");
                                            }
                                            // 推送数据给ATS处理
                                            String wayFlag = receiptFileName_no[1].equals("借") ? "1" : "2";
                                            json.append("{");
                                            json.append("\"actNum\":\"" + p_reqReceipt.actNum + "\",");
                                            json.append("\"actCur\":\"" + actCur + "\",");
                                            json.append("\"receiptCode\":\"" + receiptFileName_no[0] + "\",");// 回单编号
                                            json.append("\"receiptType\":\"" + "" + "\",");// 回单类型 1：存款回单；2：取款回单；3：转账回单；4：缴税回单；5：收费回单；6定期回单；7：活期回单
                                            json.append("\"receiptState\":\"" + "" + "\",");// 回单状态 1：正常；2：冲正；3：被冲正；4：当日冲正
                                            json.append("\"oppActName\":\"" + receiptFileName_no[4] + "\",");
                                            json.append("\"oppActNum\":\"" + receiptFileName_no[5].replace(".pdf", "") + "\",");
                                            json.append("\"amount\":\"" + receiptFileName_no[1] + "\",");
                                            json.append("\"moneyway\":\"" + wayFlag + "\",");
                                            json.append("\"tranSeqNo\":\"" + "" + "\",");
                                            json.append("\"tranCode\":\"" + "" + "\",");// 交易码?
                                            json.append("\"tranDate\":\"" + receiptFileName_no[3] + "\",");
                                            json.append("\"filePath\":\"" + AtsFilePath + "\",");// 回单文件仓库存储路径
                                            json.append("\"fileType\":\"1\"");
                                            json.append("},");
                                            sb.append(pfile + ",");
                                        } else {
                                            WriteBankLogLn("上传文件至共享目录失败，请检查共享目录配置是否正确");
                                        }
                                        //文件处理完毕，删除临时文件
                                        File file = new File(receiptDir.getPath());
                                        if (FileHelper.deleteFileIfExists(file.getPath())) {
                                            WriteBankLogLn("已删除临时文件：" + file.getPath());
                                        }
                                    } else {
                                        WriteBankLogLn("上传文件至共享目录失败，请检查共享目录配置是否正确");
                                    }
                                }
                            }
                            //删除临时文件
                            String path = download + fileName.substring(0, fileName.lastIndexOf(".pdf"));
                            if (delFile(new File(path))) {
                                WriteBankLogLn("临时文件已全部删除：" + path);
                            }
                            //删除文件(解决重复下载问题)
                            String pathFile = download + fileName;
                            if (FileHelper.deleteFileIfExists(pathFile)) {
                                WriteBankLogLn("已删除下载的pdf文件：" + path);
                            }

                        }
                    }
                } else {
                    WriteBankLogLn(tmpSbMsg);
                }
            } else {
                WriteBankLogLn(tmpStrRet[1]);
            }
            if (tmpFileCount > 0) {
                json.deleteCharAt(json.length() - 1);
                json.append("]}");
                WriteBankLogLn("推送数据到ATS的数据为：" + json.toString());
                String[] data = sendToATS(json.toString());
                if (data[0].length() == 0 && data[1].equals("ok")) {
                    WriteBankLogLn("推送数据到ATS成功,请查看数据");
                } else {
                    WriteBankLogLn("推送数据到ATS失败");
                }
            } else {
                WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
            }
            tmpCalendarFrom.add(Calendar.DATE, 1);
            tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
        }
    }

    private static TransIDHelper idHelper = new TransIDHelper(1, 99999);

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    protected static boolean delFile(File file) {
        if (!file.exists()) {
            return false;
        }

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                delFile(f);
            }
        }
        return file.delete();
    }
}